package model

import (
	"gorm.io/gorm"
	"server/internal/database"
	"time"
)

type UserAddress struct {
	Current
	Status     string `json:"status" gorm:"type:varchar(1);comment:'状态:1默认'"`
	Name       string `json:"name" gorm:"type:varchar(50);comment:'姓名'"`
	Phone      string `json:"phone" gorm:"type:varchar(11);comment:'手机'"`
	City       string `json:"city" gorm:"type:varchar(255);comment:'城市'"`
	Address    string `json:"address" gorm:"type:text;comment:'详细地址'"`
	UserID     int    `json:"user_id" gorm:"type:int;comment:'用户id'"`
	UnitName   string `json:"unit_name" gorm:"type:text;comment:'单位名称'"`
	PostalCode string `json:"postal_code" gorm:"type:text;comment:'邮政编码'"`
}

func (UserAddress) TableName() string {
	return "user_address"
}

type UserAddressModel struct {
	UserAddress
}

// Reads 列表
func (a UserAddress) Reads(Db *gorm.DB) (*gorm.DB, []UserAddress, int64) {
	var list []UserAddress
	var total int64

	Db.Model(&a).
		//Select("lc_user_bill.*,lc_user.username,lc_user.nickname,lc_user.avatar").
		//Joins("left join lc_user on lc_user_bill.user_id = lc_user.id").
		Find(&list).
		Offset(-1).
		Count(&total)
	return Db, list, total
}

// Read 单条
func (a UserAddress) Read(id any) (*gorm.DB, UserAddress) {
	Db := database.DB
	detail := UserAddress{}
	Db.Model(&a).Where("id =?", id).First(&detail)
	Db.Model(&a).
		//Select("lc_user_bill.*,lc_user.username,lc_user.nickname,lc_user.avatar").
		//Joins("left join lc_user on lc_user_bill.user_id = lc_user.id").
		First(&detail)

	return Db, detail

}

// Create 新增
func (a UserAddress) Create() *gorm.DB {
	Db := database.DB
	if a.Status == "1" {
		Db = database.DB
		b := UserAddress{}
		Db.Model(&b).Where("user_id = ? and id <> ?", a.UserID, a.ID).Update("status", "0")
	}

	t := time.Now()
	a.CreateTime = int(t.Unix())
	a.UpdateTime = int(t.Unix())
	Db = Db.Create(&a)
	return Db
}

// Update 编辑
func (a UserAddress) Update() *gorm.DB {
	Db := database.DB
	if a.Status == "1" {
		Db = database.DB
		b := UserAddress{}
		Db.Model(&b).Where("user_id = ? and id <> ?", a.UserID, a.ID).Update("status", "0")
	}
	t := time.Now()
	a.UpdateTime = int(t.Unix())
	Db = Db.Where("user_id = ?", a.UserID)
	Db.Updates(&a)

	return Db

}

// Delete 删除
func (a UserAddress) Delete(ids []int) *gorm.DB {
	Db := database.DB
	Db = Db.Where("user_id = ? and id in ?", a.UserID, ids)
	return Db.Delete(&a)

}
